package model

import (
	"errors"
	"gorm.io/gorm"
)

type (
	PlatformModel struct {
		db *gorm.DB
	}
	Platform struct {
		Model
		Name           string `form:"name" gorm:"name" json:"name"`
		PlatformId     string `form:"platform_id" gorm:"platform_id" json:"platform_id"`
		ProtocolName   string `form:"protocol_name" gorm:"protocol_name;varchar(30),not null" json:"protocol_name"`
		UserName       string `form:"user_name" gorm:"user_name;varchar(30)" json:"user_name"`
		Password       string `form:"password" gorm:"password;varchar(30)" json:"password"`
		IP             string `form:"ip" gorm:"ip;not null" json:"ip"`
		Port           string `form:"port" gorm:"port;not null" json:"port"`
		Status         bool   `form:"status" gorm:"status;not null" json:"status"`
		Ping           bool   `form:"ping" gorm:"ping" json:"ping"`
		PingTime       int64  `form:"ping_time" gorm:"ping_time" json:"ping_time"`
		Minute5        bool   `form:"minute5" gorm:"minute5" json:"minute5"`
		Hour           bool   `form:"hour" gorm:"hour" json:"hour"`
		Real           bool   `form:"real" gorm:"real" json:"real"`
		Dev            bool   `form:"dev" gorm:"dev" json:"dev"`
		Unit           string `form:"unit" gorm:"unit" json:"unit"`                                     //@unit有4种单位 ppb,ppm,ug/m3,mg/m3
		AutoReport     bool   `form:"auto_report" gorm:"auto_report" json:"auto_report"`                //是否自动上报回补数据
		ReportTime     int    `form:"report_time" gorm:"report_time" json:"report_time"`                //分钟为单位
		ReportOverTime int    `form:"report_over_time" gorm:"report_over_time" json:"report_over_time"` //回补超时时间
	}
)

func NewPlatformModel(db *gorm.DB) *PlatformModel {
	return &PlatformModel{
		db: db,
	}
}

func (m *PlatformModel) FindAll() ([]Platform, error) {
	var result []Platform
	err := m.db.Find(&result).Error
	if errors.Is(gorm.ErrRecordNotFound, err) {
		return result, nil
	}
	if err != nil {
		return nil, err
	}
	return append([]Platform{}, result...), nil
}

func (m *PlatformModel) FindById(id int64) (*Platform, error) {
	var result Platform
	err := m.db.Model(&Platform{}).Where("id = ?", id).First(&result).Error
	if errors.Is(gorm.ErrRecordNotFound, err) {
		return &result, nil
	}
	if err != nil {
		return &result, err
	}
	return &result, nil
}

func (m *PlatformModel) Add(data *Platform) error {
	return m.db.Create(data).Error
}

func (m *PlatformModel) Update(id int64, data map[string]interface{}) error {
	return m.db.Model(&Platform{}).Where("id = ?", id).Updates(data).Error
}

func (m *PlatformModel) Save(data *Platform) error {
	return m.db.Save(data).Error
}

func (m *PlatformModel) DeleteById(id int64) error {
	return m.db.Where("id = ?", id).Delete(&Platform{}).Error
}
